package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.result.PageResult;
import com.example.common.result.Result;
import com.example.controller.ZnxController;
import com.example.entity.dto.PurchaseOrder.PurmcListDto;
import com.example.entity.dto.RequisitionPurchaseDto;
import com.example.entity.dto.User.MyUser;
import com.example.entity.hz.Znx;
import com.example.entity.vo.PurchaseOrder.PurmbVo;
import com.example.entity.vo.PurchaseOrder.PurmcListVo;
import com.example.entity.vo.RequisitionPurchaseVo;
import com.example.entity.yifei.*;
import com.example.exception.BaseException;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.service.IActFlowCustomService;
import com.example.service.PurtbService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.untils.NumUtils;
import com.example.untils.SecurityUtils;
import com.example.untils.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiangPandeng
 * @since 2024-02-19
 */
@Service
public class PurtbServiceImpl extends ServiceImpl<PurtbMapper, Purtb> implements PurtbService , IActFlowCustomService {

    @Resource
    private CmsmqMapper cmsmqMapper;

    @Resource
    private PurmbMapper purmbMapper;

    @Resource
    private PurmaMapper purmaMapper;
    @Resource
    private PurtbMapper purtbMapper;
    @Resource
    private PurtaMapper purtaMapper;
    @Resource
    private PurtdMapper purtdMapper;
    @Resource
    private PurtmMapper purtmMapper;

    @Resource
    private CmsmvMapper cmsmvMapper;

    @Resource
    private InvmdMapper invmdMapper;

    @Resource
    private BuyingRequisitionMapper buyingRequisitionMapper;
//    @Override
//    @DS("mysql")
//    public void synchronous() {
//        List<BuyingRequisition> buyingRequisitionList = purtbMapper.selectAllBuyingRequisition();
//        for (BuyingRequisition buyingRequisition : buyingRequisitionList) {
//            buyingRequisitionMapper.insert(buyingRequisition);
//        }
//    }

    @Override
    public Result<PageResult> selectPage(Integer current, Integer size, RequisitionPurchaseDto requisitionPurchaseDto) {
        PageHelper.startPage(current,size,"time DESC,requisitionNo ASC,requisitionNumber ASC");

        if(StringUtils.isEmpty(requisitionPurchaseDto.getTableType())) {
            return Result.error("采购单请求类型不能为空");
        }
        if(StringUtils.isNotEmpty(requisitionPurchaseDto.getRequisitionType())){
            String[] split = requisitionPurchaseDto.getRequisitionType().split(",");
            List<String> list = new ArrayList<>(Arrays.asList(split));
            requisitionPurchaseDto.setRequisitionTypeList(list);
        }
        Page<RequisitionPurchaseVo> purchaseVoPage  = purtbMapper.selectRequisitionPurchaseVoPage(requisitionPurchaseDto);

       if (purchaseVoPage!=null){
           purchaseVoPage.getResult().forEach(arr->{
               if (arr.getMinReple()!=0&&arr.getRestockTime()!=0){
                   if (arr.getUnits().equals(arr.getUnit())&&arr.getTB043().equals(arr.getUnit())){
                       Double test = NumUtils.test(Double.valueOf(arr.getPurchased()),1.0, arr.getMinReple(), arr.getRestockTime());
//                    System.out.println("转换后的采购数量,"+"第"+purchaseVoPage.getResult().indexOf(arr)+"行:"+test);
                       double number = test/1.0;
                       test(purchaseVoPage, arr, number);
                   }else {
                       // 采购单位换算
                       Invmd invmd = this.invmdMapper.selectOne(new LambdaQueryWrapper<Invmd>().eq(Invmd::getMD001, arr.getProductNumber()).eq(Invmd::getMD002, arr.getUnits()));
                       if (invmd!=null){
//                        System.out.println("请购单号"+arr.getRequisitionNo()+",采购数量:"+arr.getPurchased());
                           Double test = NumUtils.test(Double.valueOf(arr.getPurchased()), invmd.getMD004().doubleValue(), arr.getMinReple(), arr.getRestockTime());
//                        System.out.println("转换后的采购数量,"+"第"+purchaseVoPage.getResult().indexOf(arr)+"行:"+test);
                           double number = test/invmd.getMD004().doubleValue();
                           test(purchaseVoPage, arr, number);
                       }
                   }
               }
               Double td010Double = this.purtdMapper.getTd010Double(arr.getSupplierNo(), arr.getProductNumber());
               if(td010Double!=null){
                   arr.setNuclearPriceLs(td010Double);
                   if (arr.getReferencePrice()>td010Double){
                       arr.setHistoricalunitprice(2);
                   }else if (arr.getReferencePrice().equals(td010Double)){
                       arr.setHistoricalunitprice(1);
                   }else {
                       arr.setHistoricalunitprice(0);
                   }
               }
           });

           // 单据性质
           Cmsmq cmsmq = cmsmqMapper.
                   selectOne(new LambdaQueryWrapper<Cmsmq>().eq(Cmsmq::getMq001, requisitionPurchaseDto.getTableType()));
           String mq036 = cmsmq.getMq036().trim();  // 进价控制
           // 如果品号是90000001
//           for (RequisitionPurchaseVo purchaseVo : purchaseVoPage.getResult()) {
//               if("90000001".equals(purchaseVo.getProductNumber().trim())) {
//                   RequisitionPurchaseVo temp = purtdMapper.select90000001(purchaseVo.getProductName(), purchaseVo.getSpecifications());
//                   if(temp != null) {
//                       purchaseVo.setSupplierNo(temp.getSupplierNo());
//                       purchaseVo.setSupplierName(temp.getSupplierName());
//                       purchaseVo.setCurrency(temp.getCurrency());
//                       purchaseVo.setTaxRate(temp.getTaxRate());
//                       purchaseVo.setPayment(temp.getPayment());
//                       purchaseVo.setPaymentId(temp.getPaymentId());
//                       purchaseVo.setReferencePrice(temp.getReferencePrice());
//                   }else{
//                       purchaseVo.setSupplierNo(null);
//                       purchaseVo.setSupplierName(null);
//                       purchaseVo.setCurrency(null);
//                       purchaseVo.setTaxRate(null);
//                       purchaseVo.setPayment(null);
//                       purchaseVo.setPaymentId(null);
//                       purchaseVo.setReferencePrice(null);
//                   }
//               }
//           }
           if("Y".equals(mq036)) {
               for (RequisitionPurchaseVo purchaseVo :purchaseVoPage.getResult()) {
                   List<PurmbVo> list;
                   if ("90000001".equals(purchaseVo.getProductNumber().trim())) {
                       list = purmbMapper.purmbOne
                               (new PurmcListDto(purchaseVo.getProductNumber(), purchaseVo.getProductName(), purchaseVo.getSpecifications(), purchaseVo.getUnits(),
                                       purchaseVo.getCurrency(), purchaseVo.getSupplierNo(), "", ""));
                   }else {
                       list = purmbMapper.purmbOne
                               (new PurmcListDto(purchaseVo.getProductNumber(), "", "", purchaseVo.getUnits(),
                                       purchaseVo.getCurrency(), purchaseVo.getSupplierNo(), "", ""));
                   }
                   PurchaseVoList(purchaseVo, list);
               }
           }
       }

        // 宏竹特有 设置最近的供应商信息
//        for (RequisitionPurchaseVo purchaseVo : purchaseVoPage.getResult()) {
//            if(StringUtils.isEmpty(purchaseVo.getSupplierNo())) continue;
//            // 如果有对应的核价单，优先拿核价单中的信息
//            List<PurtmListVo> list = purtmMapper.PurtmListDesc(purchaseVo.getSupplierNo(), purchaseVo.getProductNumber());
//            for(PurtmListVo vo : list) {
//                if(StringUtils.isNotEmpty(vo.getExpirationDate().trim())) {
//                    // 失效日期 >= 当前日期
//                    if(vo.getExpirationDate().compareTo(TimeUtils.HZStdTime()) >= 0) {
//                        // 赋值
//                        purchaseVo.setCurrency(vo.getCurrency());
//                        purchaseVo.setUnit(vo.getUnit());
//                        purchaseVo.setReferencePrice(vo.getUnitPrice());
//                        break;
//                    }
//                }else{
//                    // 赋值
//                    purchaseVo.setCurrency(vo.getCurrency());
//                    purchaseVo.setUnit(vo.getUnit());
//                    purchaseVo.setReferencePrice(vo.getUnitPrice());
//                    break;
//                }
//            }
//        }
        MyUser myUser = SecurityUtils.getLoginUser();
        if(myUser == null) {
            return Result.error("用户没有登录");
        }
//        Cmsmv cmsmv = cmsmvMapper.selectOne(new LambdaQueryWrapper<Cmsmv>().eq(Cmsmv::getMv079, myUser.getUsername()));
//        if(cmsmv != null) {
//            for (RequisitionPurchaseVo purchaseVo : purchaseVoPage.getResult()) {
//                purchaseVo.setCode(cmsmv.getMv001());
//                purchaseVo.setPurchaserName(cmsmv.getMv002());
//            }
//        }else{
//            for (RequisitionPurchaseVo purchaseVo : purchaseVoPage.getResult()) {
//                purchaseVo.setCode("");
//                purchaseVo.setPurchaserName("");
//            }
//        }

        PageResult pageResult = new PageResult();
        pageResult.setTotal(purchaseVoPage.getTotal());
        pageResult.setRecords(purchaseVoPage.getResult());
        return Result.success(pageResult);
    }

    private void PurchaseVoList(RequisitionPurchaseVo purchaseVo, List<PurmbVo> list) {
        for (PurmbVo item : list) {
            if ("Y".equals(item.getNumberPrice().trim())) {
                item.setNum(purchaseVo.getPurchased());
                List<PurmcListVo> purmcListVos = purmbMapper.purmcList(new PurmcListDto(item.getProductId(),"","",item.getUnit(),
                        item.getCurrency(), item.getSupplier(), item.getEffectiveDate(), purchaseVo.getPurchased()));
                if (!purmcListVos.isEmpty()){
                    for (PurmcListVo g : purmcListVos) {
                        if (Double.parseDouble(purchaseVo.getPurchased()) > g.getNumber()){
                            purchaseVo.setReferencePrice(g.getPrice());
                            // 供应商信息
                            GysXxVo(purchaseVo, item);
                            break;
                        }else {
                            purchaseVo.setReferencePrice(item.getUnitPrice());
                            // 供应商信息
                            GysXxVo(purchaseVo, item);
                        }
                    }
                }else {
                    purchaseVo.setReferencePrice(item.getUnitPrice());
                    // 供应商信息
                    GysXxVo(purchaseVo, item);
                }
            } else {
                purchaseVo.setReferencePrice(item.getUnitPrice());  // 单价
                // 供应商信息
                GysXxVo(purchaseVo, item);
            }
        }
    }

    private void GysXxVo(RequisitionPurchaseVo purchaseVo, PurmbVo item) {
        Purma purma = purmaMapper.selectOne(new LambdaQueryWrapper<Purma>()
                .eq(Purma::getMa001, item.getSupplier()));
        if(purma!=null){
            Cmsmv cmsmv = cmsmvMapper.selectOne(new LambdaQueryWrapper<Cmsmv>().eq(Cmsmv::getMv001, purma.getMa047()));
            if (cmsmv!=null){
                purchaseVo.setPurchaserNo(cmsmv.getMv001());
                purchaseVo.setPurchaserName(cmsmv.getMv002());
                purchaseVo.setPurchasing(cmsmv.getMv002());
            }
            purchaseVo.setSupplierNo(purma.getMa001());
            purchaseVo.setSupplierName(purma.getMa002());
            purchaseVo.setCurrency(item.getCurrency());
            purchaseVo.setTaxRate(purma.getMa064());
            purchaseVo.setPayment(purma.getMa025());
            purchaseVo.setPaymentId(purma.getMa055());
//                                       purchaseVo.setUnits(item.getUnit());
            purchaseVo.setTaxCategory(purma.getMa044());
        }
        return;
    }

    private void test(Page<RequisitionPurchaseVo> purchaseVoPage, RequisitionPurchaseVo arr, double number) {
        double aa;
        if (number == Math.floor(number)) {
            // 变量为整数
            aa = number;
        } else {
            // 变量不是整数
            aa = (double) Math.ceil(number);
        }
        System.out.println("转换后的采购数量,除以倍量,"+"第"+purchaseVoPage.getResult().indexOf(arr)+"行:"+aa);
        arr.setPurchased(String.valueOf(aa));
        arr.setTB044(aa);
    }

    @Override
    public Boolean tc30IsN(String tc001, String tc002) {
        LambdaQueryWrapper<Purta> queryWrapper= new LambdaQueryWrapper<Purta>();
        queryWrapper.eq(Purta::getTa001,tc001).eq(Purta::getTa002,tc002);
        Purta purta = purtaMapper.selectOne(queryWrapper);
        if (purta!=null&&purta.getTa016().equals("0")){
            return true;
        }else {
            throw new BaseException(tc001+"-"+tc002+"该请购单不是未审核请购单");
        }
    }

    @Override
    public Map<String, Object> setvariables(String id, String userName) {
        Map variables=new HashMap<>();
        variables.put("assignee0",userName);
        variables.put("processInsName","请购单流程");
        return variables;
    }

    @Override
    public Map<String, Object> setvariables(String id, String userName, Object vo) {
        return null;
    }

    @Override
    public void startRunTask(String id) {

    }
    @Autowired
private ZnxController znxController;
    @Override
    public void endRunTask(String id, Boolean state, String defineId, String initiator) {
        System.out.printf("请购单审批流程结束业务操作！！！！id="+id+"审核状态为："+state);
        String[] strings = id.split(":");
        Purta purta = purtaMapper.selectOne(new LambdaQueryWrapper<Purta>()
                .eq(Purta::getTa001, strings[0]).eq(Purta::getTa002, strings[1]));
        if(purta == null) {
            throw new CustomException("500", "请购单不存在");
        }
        if(state) {  // 审核通过
            purta.setTa016("3");
            purtaMapper.update(purta, new LambdaQueryWrapper<Purta>()
                    .eq(Purta::getTa001, strings[0]).eq(Purta::getTa002, strings[1]));
            checkPurta(strings[0], strings[1]);
            List<Znx> znxList=new ArrayList<>();
            Znx znx=Znx.builder().code(id).content("有一张新的请购单通过了审核!").departmentCode("90802").notificationCode(initiator).customField(defineId)
                    .title("通知").build();
            znxList.add(znx);
            znxController.insert(znxList);
        }else{  // 审批失败
            purta.setTa016("2");
            purtaMapper.update(purta, new LambdaQueryWrapper<Purta>()
                    .eq(Purta::getTa001, strings[0]).eq(Purta::getTa002, strings[1]));
        }
    }
    public void checkPurta(String TA001, String TA002) {
        if(StringUtils.isEmpty(TA001) || StringUtils.isEmpty(TA002)) {
            throw new CustomException("500", "单别或单号为空");
        }
        Purta purta = purtaMapper.selectOne(new LambdaQueryWrapper<Purta>().eq(Purta::getTa001, TA001).eq(Purta::getTa002, TA002));
        if(purta == null) {
            throw new CustomException("500", "单据不存在!");
        }
        purta.setTa007("Y");
        purtaMapper.update(purta, new LambdaQueryWrapper<Purta>().eq(Purta::getTa001, TA001).eq(Purta::getTa002, TA002));
        Purtb purtb = new Purtb();
        purtb.setTb025("Y");
        purtbMapper.update(purtb, new LambdaQueryWrapper<Purtb>().eq(Purtb::getTb001, TA001).eq(Purtb::getTb002, TA002));
    }
    @Override
    public Object taskInfo(Map<String, Object> processVariables) {
        return processVariables.get("object");
    }
}
